package 第二章数据结构.栈.id3302表达式求值;

import java.util.HashMap;
import java.util.Scanner;
import java.util.Stack;

/**
 * 双栈处理，处理后的栈中不含左右括号
 *      1）： 减法和除法的顺序
 *      2）： 找到完整数字
 *      3）： 栈顶优先级 <= 当前操作符 循环计算
 */
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
        char[] str = s.toCharArray();
        //定义一下加减乘除的优先级
        HashMap<Character, Integer> map = new HashMap<>();
        map.put('+', 1);
        map.put('-', 1);
        map.put('*', 2);
        map.put('/', 2);
        Stack<Integer> number_stack = new Stack<>();
        Stack<Character> op_stack = new Stack<>();
        for (int i = 0; i < str.length; i++) {
            char cur = str[i];
            //如果是数字,注意不一定是10以内的数
            if (cur >= '0' && cur <= '9') {
                int num = 0;
                int j = i;
                while (j < str.length && str[j] >= '0' && str[j] <= '9') {
                    num = num * 10 + str[j] - '0';
                    j++;
                }
                number_stack.push(num);
                i = j - 1;
            }
            else if (cur == '(') op_stack.push(cur);
            else if (cur == ')') {//进行计算直到左括号
                while (op_stack.peek() != '(') {
                    int ret = count(op_stack.pop(), number_stack.pop(), number_stack.pop());
                    number_stack.push(ret);
                }
                //弹出左括号
                op_stack.pop();
            }
            //是运算符
            else {
                while (!op_stack.isEmpty() && op_stack.peek() != '(' && map.get(op_stack.peek()) >= map.get(cur)) {
                    int ret = count(op_stack.pop(), number_stack.pop(), number_stack.pop());
                    number_stack.push(ret);
                }
                op_stack.push(cur);
            }
        }
        //栈中仍有运算符，需要使用完
        while (!op_stack.isEmpty()) {
            int ret = count(op_stack.pop(), number_stack.pop(), number_stack.pop());
            number_stack.push(ret);
        }
        System.out.println(number_stack.pop());
    }

    static int count(char c, int a, int b) {
        if (c == '+') {
            return a + b;
        } else if (c == '-') {
            return b - a;
        } else if (c == '*') {
            return a * b;
        } else
            return b / a;
    }

}






